<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/11/12
 * Time: 10:22
 */

namespace app\adminapiv3\service;


use app\common\service\HostNormalRuleGroupRelation;
use app\common\service\HostNormalRuleRelation;
use think\Db;

class NormalRuleGroup extends Base
{
    /**
     * @name 列表
     * @param $host_id
     * @param $params
     * @param int $limit
     * @return array
     * @author wx
     * @date 2019/11/12 13:24
     */
    function list($host_id, $params, $limit = 10)
    {
        //1. 更改 官方规则组的总数和使用
        $this->modifyNumUsed($host_id);

        //2. 查询数据
        $server = new \app\common\service\NormalRuleGroup();
        $list = $server->list($host_id, $params, $limit);

        return $list;
    }

    /**
     * @name 修改
     * @param $host_id
     * @param $id
     * @param $updateData
     * @return bool
     * @author wx
     * @date 2019/12/24 11:10
     */
    function modify($host_id, $id, $updateData)
    {
        $this->checkOptionHost($host_id);

        //1. 修改host_normal_group_relation
        $server = new HostNormalRuleGroupRelation();
        $server->modify(['host_id' => $host_id, 'group_id' => $id], $updateData);

        //2. 修改host_normal_rule_raletion
        $ruleServer = new HostNormalRuleRelation();
        $ruleServer->modify(['host_id' => $host_id, 'group_id' => $id], $updateData);

        $this->modifyNumUsed($host_id);



        return true;
    }



    /**
     * @name 修改总数
     * @param $host_id
     * @author wx
     * @date 2019/12/24 10:56
     */
    function modifyNumUsed($host_id)
    {
        $ruleRelationServer = new HostNormalRuleRelation();
        $total = $ruleRelationServer->total($host_id);

        $used = $ruleRelationServer->used($host_id);

        $groupRelationServer = new HostNormalRuleGroupRelation();

        foreach ($total as $k => $v){
            $num = isset($used[$k]) ? $used[$k] : 0;
            $updateData['total'] = $v;
            $updateData['used'] = $num;
            $updateData['status'] = $num == 0 ? 0 : 1;

            $groupRelationServer->modify(['host_id' => $host_id, 'group_id' => $k], $updateData);
        }
    }

    /**
     * @name: 修改处理方式
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-09-27 17:22:39
     */
    function modifyHandle ($input)
    {
        $updateData = [
            'status' => $input['status'],
            'used' => $input['status'] ? Db::raw('total') : 0
        ];

        db('HostNormalRuleGroupRelation')->where('host_id', $input['host_id'])->where('group_id', $input['group_id'])->update($updateData);
        db('HostNormalRuleRelation')->where('host_id', $input['host_id'])->where('group_id', $input['group_id'])->update(['handle'=>$input['handle'], 'status' => $input['status']]);
    }

}